package com.dyz.wsw.passport.handler;

import com.dyz.wsw.common.enumerator.ServiceCode;
import com.dyz.wsw.common.ex.ServiceException;
import com.dyz.wsw.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.reactive.resource.NoResourceFoundException;
import org.springframework.web.server.MethodNotAllowedException;
import reactor.core.publisher.Mono;

/**
 * @author dyz
 * @date 2025/2/7 18:15
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    public GlobalExceptionHandler() {
        log.info("创建全局异常处理器对象: GlobalExceptionHandler");
    }

    @ExceptionHandler
    public Mono<JsonResult> handleServiceException(ServiceException e){
        log.debug("全局异常处理器开始处理ServiceException");
        return Mono.just(JsonResult.fail(e));
    }

    @ExceptionHandler
    public Mono<JsonResult> handleWebExchangeBindException(WebExchangeBindException e){
        log.debug("全局异常处理器开始处理WebExchangeBindException");
        String message = "请求参数格式错误，"+e.getFieldError().getDefaultMessage();
        log.warn(message);
        return Mono.just(JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,"请求参数格式错误"));
    }

    @ExceptionHandler
    public Mono<JsonResult> handleNoResourceFoundException(NoResourceFoundException e){
        log.debug("全局异常处理器开始处理NoResourceFoundException");
        log.warn(e.getMessage());
        return Mono.just(JsonResult.fail(ServiceCode.ERROR_NOT_FOUND,"资源不存在"));
    }

    @ExceptionHandler
    public Mono<JsonResult> handleMethodNotAllowedException(MethodNotAllowedException e){
        log.debug("全局异常处理器开始处理MethodNotAllowedException");
        log.warn(e.getMessage());
        return Mono.just(JsonResult.fail(ServiceCode.ERROR_METHOD_NOT_ALLOWED,"请求方式错误"));
    }


    @ExceptionHandler
    public Mono<JsonResult> handleException(Throwable e){
        log.error("全局异常处理器开始处理Throwable【如果看到这个信息，请在全局异常处理器中添加对应异常处理逻辑】");
        log.error("异常跟踪信息如下：",e);
        //【看到这句时，你应该检查服务器端的控制台，并在全局异常处理器中添加处理异常的方法】
        String message = "服务器忙，请稍后再试！";
        return Mono.just(JsonResult.fail(ServiceCode.ERROR_UNKNOWN,message));
    }
}
